<?php
namespace app\modules\epi\controllers;

use Yii;
use yii\db\Expression;
use ac\controllers\AuthController;
use app\models\GoodsCategory;
use app\models\Goods;
use app\models\GoodsSearch;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use ac\behaviors\Sort;
use yii\helpers\Html;


class GoodsController extends AuthController
{
    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

    /*鉴品列表*/
    public function actionGoodsList()
    {
        if(!isset($this->get['catid'])){
            $count = 0;
            $pageSize = Tool::getPageSize();
            $currPage = 1;
            $goodsList = array();
        }else{
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            if(isset($this->get['pagesize'])){
                $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
            }else{
                $pageSize = Tool::getPageSize();
            }
            // P($this->get);
            $search = (new GoodsSearch())->search($this->get);
            if($search === false){//验证搜索参数不通过
                $count = 0;
                $goodsList = array();
            }else{
                $count = $search->count();
                $goodsList = $search->joinWith('order')
                              ->offset($pageSize*($currPage-1))->limit($pageSize)
                              ->orderBy([
                                    'add_time' => SORT_DESC
                                ])
                              // ->createCommand()->getRawSql();
                              ->asArray()->all();
            }
        }
        // P($goodsList);
        $res = array(
            'list' => $goodsList,
            'pageInfo' => array(
                'count' => intval($count),
                'currPage' => $currPage,
                'pageSize' => $pageSize,
            ),
        );
        return Tool::showRes([0, '获取成功'], $res);
    }

    /*添加鉴品*/
    public function actionAddGoods()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);

            $goods = new Goods;
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*1、添加鉴品*/
                if(!$goods_id = $goods->addGoods($this->post)){
                    $pass = false;
                    if($goods->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $goods->getErrors();//异常信息
                    }else{
                        throw new \Exception('添加鉴品失败');
                    }
                }

                /*4.增加此分类的鉴品数量， 其他分类不增加*/
                GoodsCategory::updateAllCounters(['content_count' => 1], 'catid = :id', [':id' => $this->post['Goods']['catids'][0]['catid']]);

                if($pass){
                    $backInfo = [0, '添加鉴品成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };



        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }


    /*修改鉴品*/
    public function actionModifyGoods()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            // P($this->get);
            $catid = isset($this->get['catid'])?$this->get['catid']:'';
            $goods_id = isset($this->get['id'])?$this->get['id']:'';
            if($catid or $goods_id){
                if($goods_id){
                    $goods = Goods::find()
                            ->where('goods_id = :cid', [':cid' => $goods_id])
                            ->asArray()->one();
                }else{//说明是单页,获取次栏目最大的ID数据
                    $goods = Goods::find()
                            ->where('catids = :cid', [':cid' => $catid])
                            ->orderBy(['goods_id' => SORT_DESC])
                            ->asArray()->one();
                    $goods_id = $goods['goods_id'];
                    // P($goods_id);
                }
                // P($goods);
                if(!is_null($goods)){
                    if(!empty($goods['preview'])){
                        $goods['preview'] = explode(',', $goods['preview']);
                    }else{
                        $goods['preview'] = [];
                    }

                    $data = array(
                        'goods' => $goods
                    );

                    return Tool::showRes([0, '获取成功'], $data);
                }else{
                    $data = array(
                        'goods' => ''
                    );
                    return Tool::showRes([0, '获取成功'], $data);
                };
            }
        }


        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            // P($this->post);
            $goods_id = isset($this->post['Goods']['id'])?intval($this->post['Goods']['id']):'';
            if(!$goods_id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{

                    /*修改鉴品信息*/
                    $goods = new Goods;
                    if(!$goods->modifyGoods($this->post, $goods_id)){
                        $pass = false;
                        if($goods->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $goods->getErrors();//异常信息
                        }else{
                            throw new \Exception('修改鉴品失败');
                        }
                    }
                    /*如果是挪动栏目，需要把就栏目的数据总数减一，新栏目加一*/
                    if(isset($this->post['Goods']['mark']) and 
                        $this->post['Goods']['mark'] == 'setCategory' and
                        ($this->post['Goods']['oldcatid'] != $this->post['Goods']['catids'][0]['catid'])){
                        /*老栏目减一*/
                        GoodsCategory::updateAllCounters(['content_count' => -1], 'catid = :catid', [':catid' => $this->post['Goods']['oldcatid']]);
                        /*新栏目加一*/
                        GoodsCategory::updateAllCounters(['content_count' => 1], 'catid = :catid', [':catid' => $this->post['Goods']['catids'][0]['catid']]);
                    }


                    if($pass){
                        $backInfo = [0, '修改鉴品成功'];//返回信息
                        $transaction->commit();
                    }

                }catch(\Exception $exception){
                    $transaction->rollback();       
                };   
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }

        return Tool::showRes(ErrMap::getError(10005));
    }


    /*设置状态*/
    public function actionSetGoodsState()
    {
        $id = isset($this->post['id'])?$this->post['id']:'';
        $flag = isset($this->post['flag'])?$this->post['flag']:'';
        $type = gettype($id);
        if($id and ($type == 'string' or $type == 'array') and in_array($flag, [1,2,3,5])) {
            $goods = new Goods;
            if($type == 'string'){//单个
                if($goods->updateAll(['state' => $flag], 'goods_id = :id', [':id' => $id])){//成功
                    $backInfo = [0, '更改鉴品状态成功'];//返回信息
                }else{//失败
                    $backInfo = ErrMap::getError(10013, '更改鉴品状态失败');//返回信息
                }
            }
            if($type == 'array'){//批量
                if($goods->updateAll(['state' => $flag], ['in', 'goods_id', $id])){//成功
                    $backInfo = [0, '更改鉴品状态成功'];//返回信息
                }else{//失败
                    $backInfo = ErrMap::getError(10013, '更改鉴品状态失败');//返回信息
                }
            }

            if(!isset($exception)){
                $exception = '';//异常信息
            }

            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除鉴品*/
    public function actionDeleteGoods()
    {
        $id = isset($this->post['id'])?$this->post['id']:'';
        $type = gettype($id);
        if($id and ($type == 'string' or $type == 'array')){
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                if($type == 'string'){//单个删除
                    $goods = Goods::find()->where('goods_id = :id', [':id' => $id])->one();
                    if(!is_null($goods)){
                        /*删除鉴品*/
                        if(!$goods->delete()){
                            $backInfo = ErrMap::getError(10013, '删除鉴品失败');//返回信息
                            $pass = false;
                        }

                        /*减少此分类的鉴品数量， 其他分类不减少*/
                        if($pass){
                            $tmp = explode(',', $goods->catids);
                            if($pass and !GoodsCategory::updateAllCounters(['content_count' => -1], 'catid = :id', [':id' => $tmp[0]])){
                                $backInfo = ErrMap::getError(10013, '删除鉴品失败');//返回信息
                                $pass = false;
                            }
                        }
                    }
                }
                if($type == 'array'){//批量删除
                    foreach($id as $k => $v){
                        $goods = Goods::find()->where('goods_id = :id', [':id' => $v])->one();
                        if(!is_null($goods)){
                            /*删除鉴品*/
                            if(!$goods->delete()){
                                $backInfo = ErrMap::getError(10013, '删除鉴品失败');//返回信息
                                $pass = false;
                            }
                            /*减少此分类的鉴品数量， 其他分类不减少*/
                            $tmp = explode(',', $goods->catids);
                            if($pass){
                                GoodsCategory::updateAllCounters(['content_count' => -1], 'catid = :id', [':id' => $tmp[0]]);
                            }
                        }
                    }
                }

                if($pass){
                    $backInfo = [0, '删除鉴品成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*排序*/
    public function actionSetSort()
    {
        if(Yii::$app->request->isPost){
            $sort = $this->post['sort'];
            // P($sort);
            if(!empty($sort) and is_array($sort)){
                if($this->setSortList(new Goods, $sort)){
                    $backInfo = [0, '设置鉴品排序成功'];//返回信息
                }

            }
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


}
